import 'package:xiaofanshu_flutter/models/browse_history.dart';
import 'package:xiaofanshu_flutter/utils/db_util.dart';

class BrowseHistoryMapper {
  final DBManager _dbManager = DBManager.instance;

  // 创建浏览记录表
  Future<void> createBrowseHistoryTable() async {
    await _dbManager.createTable('''
      CREATE TABLE IF NOT EXISTS browse_history (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        noteId TEXT UNIQUE,
        title TEXT,
        coverPicture TEXT,
        type INTEGER,
        browseTime INTEGER,
        authorId TEXT,
        authorName TEXT
      );
    ''');
  }

  // 添加浏览记录
  Future<void> addHistory(BrowseHistory history) async {
    // 如果记录已存在，先删除旧的再添加新的（保持最新时间）
    await deleteHistoryByNoteId(history.noteId);
    
    final db = await _dbManager.database;
    await db.insert('browse_history', history.toMap());
  }

  // 获取所有浏览记录，按时间倒序
  Future<List<BrowseHistory>> getAllHistory() async {
    final db = await _dbManager.database;
    final List<Map<String, dynamic>> maps = await db.query(
      'browse_history',
      orderBy: 'browseTime DESC',
    );

    return List.generate(maps.length, (i) {
      return BrowseHistory.fromMap(maps[i]);
    });
  }

  // 删除单条记录
  Future<void> deleteHistory(int id) async {
    final db = await _dbManager.database;
    await db.delete(
      'browse_history',
      where: 'id = ?',
      whereArgs: [id],
    );
  }

  // 根据noteId删除记录
  Future<void> deleteHistoryByNoteId(String noteId) async {
    final db = await _dbManager.database;
    await db.delete(
      'browse_history',
      where: 'noteId = ?',
      whereArgs: [noteId],
    );
  }

  // 清空所有记录
  Future<void> clearAllHistory() async {
    final db = await _dbManager.database;
    await db.delete('browse_history');
  }

  // 获取记录数量
  Future<int> getHistoryCount() async {
    final db = await _dbManager.database;
    final result = await db.rawQuery('SELECT COUNT(*) FROM browse_history');
    return result.first.values.first as int;
  }
}